package com.llyb.controller;

import com.llyb.inter.ChatAssistant;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@Slf4j
public class StreamingChatModelController {

    @Autowired
    private StreamingChatModel streamingChatModel;

    @Autowired
    private ChatAssistant chatAssistant;



    // http://localhost:9007/chatstream/chat
    @GetMapping("/chatstream/chat")
    public Flux<String> chatStream(@RequestParam(value = "prompt", defaultValue = "天津有什么好吃") String prompt) {

        return Flux.create(stringFluxSink -> {
            streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) {
                    stringFluxSink.next(s);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {
                    stringFluxSink.complete();
                }

                @Override
                public void onError(Throwable throwable) {
                    stringFluxSink.error(throwable);
                }
            });
        });
    }

    @GetMapping("/chatstream/chat2")
    public void chatStreamVoid(@RequestParam(value = "prompt", defaultValue = "北京有什么好吃") String prompt) {


        streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {
            @Override
            public void onPartialResponse(String s) {
                System.out.println(s);
            }

            @Override
            public void onCompleteResponse(ChatResponse chatResponse) {
                System.out.println("---response over: "+chatResponse);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }

    @GetMapping("/chatstream/chat3")
    public Flux<String> chat3(@RequestParam(value = "prompt", defaultValue = "南京有什么好吃") String prompt)
    {
        System.out.println("---come in chat3");

        return chatAssistant.chatFlux(prompt);
    }



}
